<!DOCTYPE html>
<html>
<head>
    <title>AI对话</title>
    <style>
        .container { max-width: 800px; margin: 0 auto; padding: 20px; }
        .chat-box { height: 500px; border: 1px solid #ccc; margin: 20px 0; padding: 10px; overflow-y: auto; }
        .user-msg { background: #e3f2fd; padding: 10px; margin: 5px; border-radius: 10px; text-align: right; max-width: 70%; margin-left: auto; }
        .ai-msg { background: #f5f5f5; padding: 10px; margin: 5px; border-radius: 10px; text-align: left; max-width: 70%; }
        .input-area { display: flex; gap: 10px; }
        input[type="text"] { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 5px; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; }
        .search-box { margin-bottom: 20px; display: flex; gap: 10px; }
        input[type="datetime-local"] { padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        .history-item { margin-bottom: 15px; border-bottom: 1px solid #eee; padding-bottom: 10px; }
        .history-item span { color: #666; font-size: 0.8em; display: block; margin-bottom: 5px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="search-box">
            <input type="text" id="searchUserId" placeholder="用户ID">
            <input type="datetime-local" id="startTime">
            <input type="datetime-local" id="endTime">
            <button onclick="search()">搜索</button>
        </div>

        <div id="chatBox" class="chat-box"></div>

        <div class="input-area">
            <input type="text" id="msgInput" placeholder="输入消息...">
            <button onclick="send()">发送</button>
        </div>
    </div>

    <script>
        let uid = localStorage.getItem('userId') || crypto.randomUUID();
        localStorage.setItem('userId', uid);

        async function send() {
            const userInput = document.getElementById('msgInput');
            const chatBox = document.getElementById('chatBox');

            chatBox.innerHTML += `<div class="user-msg">${userInput.value}</div>`;

            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        user_id: uid,
                        msg: userInput.value
                    })
                });

                const data = await response.json();

                if (data.error) {
                    chatBox.innerHTML += `<div class="ai-msg">${data.error}</div>`;
                    return;
                }

                chatBox.innerHTML += `<div class="ai-msg">${data.reply}</div>`;
                userInput.value = '';
                chatBox.scrollTop = chatBox.scrollHeight;
            } catch {
                chatBox.innerHTML += '<div class="ai-msg">网络请求失败</div>';
            }
        }

        async function search() {
            const chatBox = document.getElementById('chatBox');
            chatBox.innerHTML = '<div class="ai-msg">查询中...</div>';

            try {
                const params = new URLSearchParams({
                    user_id: document.getElementById('searchUserId').value,
                    start_time: document.getElementById('startTime').value,
                    end_time: document.getElementById('endTime').value
                });

                const response = await fetch(`/history?${params}`);
                const history = await response.json();

                if (history.error) {
                    chatBox.innerHTML = `<div class="ai-msg">${history.error}</div>`;
                    return;
                }

                chatBox.innerHTML = history.length ? history.map(item => `
                    <div class="history-item">
                        <span>[${new Date(item.time).toLocaleString()}]</span>
                        <div class="user-msg">${item.msg}</div>
                        <div class="ai-msg">${item.reply}</div>
                    </div>
                `).join('') : '<div class="ai-msg">未找到相关记录</div>';
            } catch {
                chatBox.innerHTML = '<div class="ai-msg">搜索请求失败</div>';
            }
        }
    </script>
</body>
</html>